package com.fwtai.service.web;

import com.fwtai.bean.PageFormData;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import com.fwtai.tool.ToolString;
import com.fwtai.web.GoodsOrderDao;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.CompletableFuture;

/**
 * 微信支付订单业务层
 * @作者 李宇鹏
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2023-04-11 13:44:15
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class GoodsOrderService{

  private final GoodsOrderDao goodsOrderDao;

  private final ThreadPoolTaskExecutor taskExecutor;

  public GoodsOrderService(final GoodsOrderDao goodsOrderDao,final ThreadPoolTaskExecutor taskExecutor){
    this.goodsOrderDao = goodsOrderDao;
    this.taskExecutor = taskExecutor;
  }

  public String add(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request);
      final String p_user_id = "user_id";
      final String p_buyer_type = "buyer_type";
      final String p_openId = "openId";
      final String p_transaction_id = "transaction_id";
      final String p_out_trade_no = "out_trade_no";
      final String p_total_fee = "total_fee";
      final String p_status = "status";
      final String p_evaluate = "evaluate";
      final String p_refund = "refund";
      final String p_version = "version";
      final String p_body = "body";
      final String p_pay_date = "pay_date";
      final String validate = ToolClient.validateField(formData,p_user_id,p_buyer_type,p_openId,p_out_trade_no,p_total_fee,p_status,p_evaluate,p_refund,p_version,p_body);
      if(validate != null) return validate;
      final String len_user_id = formData.getString(p_user_id);
      if(len_user_id != null && len_user_id.length() > 19){
        return ToolClient.createJsonFail("购买人|付费用户id字数太多");
      }
      final String len_buyer_type = formData.getString(p_buyer_type);
      if(len_buyer_type != null && len_buyer_type.length() > 1){
        return ToolClient.createJsonFail("购买类型（1是用户购买；2是直营店向区级购买；3区级向总公司购买）字数太多");
      }
      final String len_openId = formData.getString(p_openId);
      if(len_openId != null && len_openId.length() > 40){
        return ToolClient.createJsonFail("微信的openId字数太多");
      }
      final String len_transaction_id = formData.getString(p_transaction_id);
      if(len_transaction_id != null && len_transaction_id.length() > 64){
        return ToolClient.createJsonFail("交易标识码（交易单号）字数太多");
      }
      final String len_out_trade_no = formData.getString(p_out_trade_no);
      if(len_out_trade_no != null && len_out_trade_no.length() > 19){
        return ToolClient.createJsonFail("订单号字数太多");
      }
      final String len_total_fee = formData.getString(p_total_fee);
      if(len_total_fee != null && len_total_fee.length() > 15){
        return ToolClient.createJsonFail("支付金额字数太多");
      }
      final String len_status = formData.getString(p_status);
      if(len_status != null && len_status.length() > 1){
        return ToolClient.createJsonFail("支付状态(0未支付;1已支付)字数太多");
      }
      final String len_evaluate = formData.getString(p_evaluate);
      if(len_evaluate != null && len_evaluate.length() > 1){
        return ToolClient.createJsonFail("评价状态(0待评价;1已评价)字数太多");
      }
      final String len_refund = formData.getString(p_refund);
      if(len_refund != null && len_refund.length() > 1){
        return ToolClient.createJsonFail("退款状态(0未退款;1已退款)字数太多");
      }
      final String len_version = formData.getString(p_version);
      if(len_version != null && len_version.length() > 10){
        return ToolClient.createJsonFail("版本号(乐观锁)字数太多");
      }
      final String len_body = formData.getString(p_body);
      if(len_body != null && len_body.length() > 128){
        return ToolClient.createJsonFail("支付描述（下单描述）字数太多");
      }
      final String len_pay_date = formData.getString(p_pay_date);
      if(len_pay_date != null && len_pay_date.length() > 10){
        return ToolClient.createJsonFail("付款日期（支付成功后更新）字数太多");
      }
      final Long v_user_id = formData.getLong(p_user_id);
      if(v_user_id == null){
        return ToolClient.createJsonFail("购买人|付费用户id不是有效的数据格式");
      }else{
        formData.put(p_user_id,v_user_id);
      }
      final Integer v_buyer_type = formData.getInteger(p_buyer_type);
      if(v_buyer_type == null){
        return ToolClient.createJsonFail("购买类型（1是用户购买；2是直营店向区级购买；3区级向总公司购买）不是有效的数字");
      }else{
        formData.put(p_buyer_type,v_buyer_type);
      }
      final Long v_out_trade_no = formData.getLong(p_out_trade_no);
      if(v_out_trade_no == null){
        return ToolClient.createJsonFail("订单号不是有效的数据格式");
      }else{
        formData.put(p_out_trade_no,v_out_trade_no);
      }
      final BigDecimal v_total_fee = formData.getBigDecimal(p_total_fee);
      if(v_total_fee == null){
        return ToolClient.createJsonFail("支付金额不是有效的数字");
      }else{
        formData.put(p_total_fee,v_total_fee);
      }
      final Integer v_status = formData.getInteger(p_status);
      if(v_status == null){
        return ToolClient.createJsonFail("支付状态(0未支付;1已支付)不是有效的数字");
      }else{
        formData.put(p_status,v_status);
      }
      final Integer v_evaluate = formData.getInteger(p_evaluate);
      if(v_evaluate == null){
        return ToolClient.createJsonFail("评价状态(0待评价;1已评价)不是有效的数字");
      }else{
        formData.put(p_evaluate,v_evaluate);
      }
      final Integer v_refund = formData.getInteger(p_refund);
      if(v_refund == null){
        return ToolClient.createJsonFail("退款状态(0未退款;1已退款)不是有效的数字");
      }else{
        formData.put(p_refund,v_refund);
      }
      final Integer v_version = formData.getInteger(p_version);
      if(v_version == null){
        return ToolClient.createJsonFail("版本号(乐观锁)不是有效的数字");
      }else{
        formData.put(p_version,v_version);
      }
      final Integer v_pay_date = formData.getInteger(p_pay_date);
      if(v_pay_date == null){
        return ToolClient.createJsonFail("付款日期（支付成功后更新）不是有效的数字");
      }else{
        formData.put(p_pay_date,v_pay_date);
      }
      formData.put("kid",new IdBuilder().getId121L());//todo 视情况是否需要处理主键重复的而需要删除所上传的文件,如以用户主键创建的表,可使用唯一键约束并结合IGNORE使用
      return ToolClient.executeRows(goodsOrderDao.add(formData));
    },taskExecutor).join();
  }

  public String edit(final HttpServletRequest request){
    return CompletableFuture.supplyAsync(()->{
      final PageFormData formData = new PageFormData(request);
      final String p_kid = "kid";
      final String p_user_id = "user_id";
      final String p_buyer_type = "buyer_type";
      final String p_openId = "openId";
      final String p_transaction_id = "transaction_id";
      final String p_out_trade_no = "out_trade_no";
      final String p_total_fee = "total_fee";
      final String p_status = "status";
      final String p_evaluate = "evaluate";
      final String p_refund = "refund";
      final String p_version = "version";
      final String p_body = "body";
      final String p_pay_date = "pay_date";
      final String validate = ToolClient.validateField(formData,p_kid,p_user_id,p_buyer_type,p_openId,p_out_trade_no,p_total_fee,p_status,p_evaluate,p_refund,p_version,p_body);
      if(validate != null) return validate;
      final String len_user_id = formData.getString(p_user_id);
      if(len_user_id != null && len_user_id.length() > 19){
        return ToolClient.createJsonFail("购买人|付费用户id字数太多");
      }
      final String len_buyer_type = formData.getString(p_buyer_type);
      if(len_buyer_type != null && len_buyer_type.length() > 1){
        return ToolClient.createJsonFail("购买类型（1是用户购买；2是直营店向区级购买；3区级向总公司购买）字数太多");
      }
      final String len_openId = formData.getString(p_openId);
      if(len_openId != null && len_openId.length() > 40){
        return ToolClient.createJsonFail("微信的openId字数太多");
      }
      final String len_transaction_id = formData.getString(p_transaction_id);
      if(len_transaction_id != null && len_transaction_id.length() > 64){
        return ToolClient.createJsonFail("交易标识码（交易单号）字数太多");
      }
      final String len_out_trade_no = formData.getString(p_out_trade_no);
      if(len_out_trade_no != null && len_out_trade_no.length() > 19){
        return ToolClient.createJsonFail("订单号字数太多");
      }
      final String len_total_fee = formData.getString(p_total_fee);
      if(len_total_fee != null && len_total_fee.length() > 15){
        return ToolClient.createJsonFail("支付金额字数太多");
      }
      final String len_status = formData.getString(p_status);
      if(len_status != null && len_status.length() > 1){
        return ToolClient.createJsonFail("支付状态(0未支付;1已支付)字数太多");
      }
      final String len_evaluate = formData.getString(p_evaluate);
      if(len_evaluate != null && len_evaluate.length() > 1){
        return ToolClient.createJsonFail("评价状态(0待评价;1已评价)字数太多");
      }
      final String len_refund = formData.getString(p_refund);
      if(len_refund != null && len_refund.length() > 1){
        return ToolClient.createJsonFail("退款状态(0未退款;1已退款)字数太多");
      }
      final String len_version = formData.getString(p_version);
      if(len_version != null && len_version.length() > 10){
        return ToolClient.createJsonFail("版本号(乐观锁)字数太多");
      }
      final String len_body = formData.getString(p_body);
      if(len_body != null && len_body.length() > 128){
        return ToolClient.createJsonFail("支付描述（下单描述）字数太多");
      }
      final String len_pay_date = formData.getString(p_pay_date);
      if(len_pay_date != null && len_pay_date.length() > 10){
        return ToolClient.createJsonFail("付款日期（支付成功后更新）字数太多");
      }
      final Long v_user_id = formData.getLong(p_user_id);
      if(v_user_id == null){
        return ToolClient.createJsonFail("购买人|付费用户id不是有效的数据格式");
      }else{
        formData.put(p_user_id,v_user_id);
      }
      if(len_buyer_type != null){
        final Integer v_buyer_type = formData.getInteger(p_buyer_type);
        if(v_buyer_type == null){
          return ToolClient.createJsonFail("购买类型（1是用户购买；2是直营店向区级购买；3区级向总公司购买）不是有效的数字");
        }else{
          formData.put(p_buyer_type,v_buyer_type);
        }
      }
      final Long v_out_trade_no = formData.getLong(p_out_trade_no);
      if(v_out_trade_no == null){
        return ToolClient.createJsonFail("订单号不是有效的数据格式");
      }else{
        formData.put(p_out_trade_no,v_out_trade_no);
      }
      final BigDecimal v_total_fee = formData.getBigDecimal(p_total_fee);
      if(v_total_fee == null){
        return ToolClient.createJsonFail("支付金额不是有效的数字");
      }else{
        formData.put(p_total_fee,v_total_fee);
      }
      if(len_status != null){
        final Integer v_status = formData.getInteger(p_status);
        if(v_status == null){
          return ToolClient.createJsonFail("支付状态(0未支付;1已支付)不是有效的数字");
        }else{
          formData.put(p_status,v_status);
        }
      }
      if(len_evaluate != null){
        final Integer v_evaluate = formData.getInteger(p_evaluate);
        if(v_evaluate == null){
          return ToolClient.createJsonFail("评价状态(0待评价;1已评价)不是有效的数字");
        }else{
          formData.put(p_evaluate,v_evaluate);
        }
      }
      if(len_refund != null){
        final Integer v_refund = formData.getInteger(p_refund);
        if(v_refund == null){
          return ToolClient.createJsonFail("退款状态(0未退款;1已退款)不是有效的数字");
        }else{
          formData.put(p_refund,v_refund);
        }
      }
      if(len_version != null){
        final Integer v_version = formData.getInteger(p_version);
        if(v_version == null){
          return ToolClient.createJsonFail("版本号(乐观锁)不是有效的数字");
        }else{
          formData.put(p_version,v_version);
        }
      }
      if(len_pay_date != null){
        final Integer v_pay_date = formData.getInteger(p_pay_date);
        if(v_pay_date == null){
          return ToolClient.createJsonFail("付款日期（支付成功后更新）不是有效的数字");
        }else{
          formData.put(p_pay_date,v_pay_date);
        }
      }
      final Long v = goodsOrderDao.queryExistById(formData.getLong(p_kid));
      if(v == null){
        return ToolClient.createJsonFail("数据不存在,刷新重试");
      }
      formData.put(p_kid,formData.getLong(p_kid));
      return ToolClient.executeRows(goodsOrderDao.edit(formData));
    },taskExecutor).join();
  }

  public String queryById(final Long kid){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      final HashMap<String,Object> map = goodsOrderDao.queryById(kid);
      final List<HashMap<String,Object>> list = goodsOrderDao.getOrderDetails(kid);
      final HashMap<String,Object> result = new HashMap<>(2);
      result.put("goodsOrder",map);
      if(list != null){
        result.put("orderDetails",list);
      }
      return ToolClient.queryJson(result);
    },taskExecutor).join();
  }

  //编辑时的文件删除可参考此方法
  public String delById(final Long kid){
    //若用到ThreadLocal的数据可在此组装
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        return ToolClient.jsonValidateField();
      }
      return ToolClient.executeRows(goodsOrderDao.delById(kid),"操作成功","删除失败,刷新重试");
    },taskExecutor).join();
  }

  public String delByKeys(final String ids){
    return CompletableFuture.supplyAsync(()->{
      if(ids == null || ids.length() <= 0){
        return ToolClient.jsonValidateField();
      }
      final long[] list = ToolString.keysToArarry(ids);
      if(list == null){
        return ToolClient.createJsonFail("请选择要删除的数据");
      }
      return ToolClient.executeRows(goodsOrderDao.delByKeys(list),"操作成功","数据不存在,刷新重试");
    },taskExecutor).join();
  }

  public String updateAvailable(final String kid,final String available,final String out_trade_no){
    return CompletableFuture.supplyAsync(()->{
      if(kid == null){
        if(out_trade_no == null){
          return ToolClient.jsonValidateField();
        }
        return ToolClient.executeRows(goodsOrderDao.editAvailable(Long.parseLong(out_trade_no)),"全部停止兑换成功","停止失败");
      }else{
        if(available == null){
          return ToolClient.jsonValidateField();
        }
        final HashMap<String,Object> params = new HashMap<>(2);
        params.put("available",Integer.parseInt(available));
        params.put("kid",Long.parseLong(kid));
        return ToolClient.executeRows(goodsOrderDao.updateAvailable(params));
      }
    },taskExecutor).join();
  }

  public String listData(final PageFormData formData){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(ToolClient.dataTableMysql(formData) == null) return ToolClient.jsonValidateField();
        final CompletableFuture<List<HashMap<String,Object>>> listData = CompletableFuture.supplyAsync(() -> goodsOrderDao.getListData(formData),taskExecutor);
        final CompletableFuture<Integer> listTotal = CompletableFuture.supplyAsync(() -> goodsOrderDao.getListTotal(formData),taskExecutor);
        //CompletableFuture.allOf(listData,listTotal).join();//若出错取消注释即可
        return ToolClient.dataTableOK(listData.join(),listTotal.join());
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }

  public String listOrderCoupon(final Long outTradeNo){
    return CompletableFuture.supplyAsync(()->{
      try{
        if(outTradeNo == null){
          return ToolClient.jsonValidateField();
        }
        return ToolClient.queryJson(goodsOrderDao.listOrderCoupon(outTradeNo));
      } catch (final Exception ignored){
        return ToolClient.dataTableException();
      }
    },taskExecutor).join();
  }
}